package com.umeox.watch.moto.launcher.fragment;


import static com.umeox.moto.common.log.Logger.getTime;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.DateUtils;
import com.umeox.moto.watch.themes.app.ThemeFragment;
import com.umeox.moto.watch.themes.widget.ProgressView;
import com.umeox.moto.watch.themes.widget.RoundedImageView;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.adapter.ChallengeAdapter;
import com.umeox.watch.moto.launcher.base.GlideApp;
import com.umeox.watch.moto.launcher.bean.TodayChallengeBean;
import com.umeox.watch.moto.pedometer.base.QuranChallenge;
import com.umeox.watch.moto.pedometer.base.TodayChallenge;
import com.umeox.watch.moto.pedometer.data.PedometerContract;
import com.umeox.watch.moto.pedometer.data.PedometerPresenter;
import com.umeox.watch.moto.pedometer.util.CacheImpl;
import com.umeox.watch.moto.pedometer.util.StepManager;
import com.umeox.watch.moto.pedometer.util.StepUtils;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

public class PedometerFragment extends ThemeFragment implements PedometerContract.View, StepManager.OnPedometerRegisteredListener, ChallengeAdapter.OnItemClickListener {

    public static final long INTERVAL_STEPS_UPLOAD = TimeUnit.SECONDS.toMillis(30);

    private PedometerContract.Presenter mPresenter;

    private int mStepTarget = 5000, goalTimes = 0, todayStepCount;
    private boolean reachGoal = false;

    private TextView mStepCountTv;
    private ProgressView mStepProgressView;
    private TextView mCaloriesTv;
    private TextView mDistancesTv, mRewardsTv;


    private TextView dateTv;
    private TextView minHeartTv;
    private TextView maxHeartTv;
    private TextView averageHeartTv;
    private RoundedImageView ivAvatar;

    private long mTime;
    private int mDistanceUnit;
    Handler mHandler = new Handler();
    private double mAccountHeight;
    private double mAccountWeight;
    private final DecimalFormat decimalFormat = new DecimalFormat("#.##");
    private RecyclerView mChallengeRv;
    private ChallengeAdapter mChallengeAdapter;

    public PedometerFragment() {
        mPresenter = new PedometerPresenter(this);
    }

    public static final String EXTRA_KEY_ID = "id";
    public static final String EXTRA_KEY_AUTO = "auto";

    @Override
    protected int getLayoutId() {
        return R.layout.frag_pedometer;
    }

    @Override
    protected void initView(View rootView) {
        mStepCountTv = rootView.findViewById(R.id.tv_current_step);
        mStepProgressView = rootView.findViewById(R.id.step_progress);
        mCaloriesTv = rootView.findViewById(R.id.tv_calories);
        mDistancesTv = rootView.findViewById(R.id.tv_distances);
        mRewardsTv = rootView.findViewById(R.id.tv_rewards);

        dateTv = rootView.findViewById(R.id.tv_date);
        minHeartTv = rootView.findViewById(R.id.tv_min_heart);
        maxHeartTv = rootView.findViewById(R.id.tv_max_heart);
        averageHeartTv = rootView.findViewById(R.id.tv_average_heart);
        ivAvatar = rootView.findViewById(R.id.iv_avatar);

        mChallengeRv = rootView.findViewById(R.id.rv_challenge);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mChallengeRv.setLayoutManager(linearLayoutManager);
        mChallengeRv.setHasFixedSize(true);
        mChallengeAdapter = new ChallengeAdapter(mContext);
        mChallengeRv.setAdapter(mChallengeAdapter);
        mChallengeAdapter.setOnItemClickListener(this);

        mDistanceUnit = DataProvider.getDistanceUnit();
        mAccountHeight = DataProvider.getHeight();
        mAccountWeight = DataProvider.getWeight();
        mPresenter.onCreate();
        StepManager.getInstance().setOnPedometerRegisteredListener(this);
        initData();
//        saveSteps();
    }

    /**
     * test savae
     */
    public void saveSteps() {
//        mPresenter.saveSteps();
        mHandler.postDelayed(this::saveSteps, TimeUnit.SECONDS.toMillis(60));
    }


    private void initData() {
//        mPresenter.getStepInfo();
        mTime = getTime(0);
//        mPresenter.uploadSteps(0);
        String holderAvatar = DataProvider.getAvatar();
        Log.d(TAG, "initData: " + holderAvatar);
        mRewardsTv.setText(String.format(Locale.getDefault(), "%d", DataProvider.getSportsChallengeRewardsValue() + DataProvider.getQuranChallengeRewardsValue()));
        if (!TextUtils.isEmpty(holderAvatar)) {
            GlideApp.with(mContext)
                    .load(holderAvatar)
                    .circleCrop()
                    .into(ivAvatar);
        }

    }

    private void initHeartRateData() {
        List<ContentValues> values = DataProvider.getHeartRatesByLimit(1);
        if (values != null && values.size() > 0) {
            ContentValues contentValues = values.get(0);
            dateTv.setText(DateUtils.formatDateTime(contentValues.getAsLong(DataProvider.HeartRateProvider.MEASURE_TIME), "HH:mm,MM-dd"));
            minHeartTv.setText(contentValues.getAsString(DataProvider.HeartRateProvider.MIN_VALUE));
            maxHeartTv.setText(contentValues.getAsString(DataProvider.HeartRateProvider.MAX_VALUE));
            averageHeartTv.setText(contentValues.getAsString(DataProvider.HeartRateProvider.AVERAGE_VALUE));
        }
    }


    private void updateUI() {
        if (todayStepCount >= mStepTarget && !reachGoal) {
            reachGoal = true;
            goalTimes += 1;
            CacheImpl.getInstance().put(DataProvider.StepInfoProvider.REACH_GOAL, true);
            CacheImpl.getInstance().put(DataProvider.StepInfoProvider.REACH_GOAL_TIMES, goalTimes);
//            mPresenter.uploadSteps(todayStepCount);
        }
        float percent = (float) todayStepCount / mStepTarget;
        NumberFormat nf = new DecimalFormat("#,###", new DecimalFormatSymbols(Locale.ROOT));
        String str = nf.format(todayStepCount);

        mStepCountTv.setText(str);
        mStepProgressView.setProgress(percent);
        setDistanceCalories();
    }

    private void setDistanceCalories() {
        if (getContext() == null) {
            Log.d(TAG, "setDistanceCalories: context is null");
            return;
        }
        double stepDistance = StepUtils.getDistance(mAccountHeight);
        DecimalFormat df = new DecimalFormat("###.0", new DecimalFormatSymbols(Locale.ROOT));
        double distance = stepDistance * todayStepCount;
        double calories = StepUtils.getKcal(mAccountWeight, distance / 100 / 1000);
        mCaloriesTv.setText(String.valueOf(calories));
        final String[] distanceUnits = mContext.getResources().getStringArray(R.array.Unit_Distance);
        final double v = distance / (mDistanceUnit == 1 ? 100000 : 160900);
        mDistancesTv.setText(decimalFormat.format(todayStepCount == 0 ? 0 : Math.max(v, 0.01)));

    }


    @Override
    public void onStepCountChange(int stepCounts) {
        Logger.e("=======onStepCountChange========todayStepCount=" + todayStepCount);
        todayStepCount = stepCounts;
        sendStepInfoChange();
        updateUI();
        if (getTime(mTime) >= INTERVAL_STEPS_UPLOAD) {
            Logger.e("=======STEPS_UPLOAD======todayStepCount=" + todayStepCount);
            mTime = getTime(0);
//            mPresenter.uploadSteps(stepCounts);
        }
    }

    @Override
    public void onStepInfoChange(int stepTarget) {
        if (mContext == null) {
            return;
        }
        mStepTarget = stepTarget;
        sendStepInfoChange();
        updateUI();
    }


    private void sendStepInfoChange() {
        final LinkedHashSet<StepManager.StepInfoChangeListener> listeners = StepManager.getInstance().getListeners();
        for (StepManager.StepInfoChangeListener listener : listeners) {
            listener.onStepInfoChange(todayStepCount, mStepTarget, mAccountHeight, mAccountWeight);
        }
    }

    @Override
    public void onHolderInfoChange() {

        if (mContext == null) {
            return;
        }
        Logger.e(TAG, "onHolderInfoChange,RewardsTotalValue= " + DataProvider.getSportsChallengeRewardsValue() + DataProvider.getQuranChallengeRewardsValue());
        mRewardsTv.setText(String.format(Locale.getDefault(), "+%d", DataProvider.getSportsChallengeRewardsValue() + DataProvider.getQuranChallengeRewardsValue()));
        mAccountHeight = DataProvider.getHeight();
        mAccountWeight = DataProvider.getWeight();
        sendStepInfoChange();
        setDistanceCalories();
        String holderAvatar = DataProvider.getAvatar();
        if (!TextUtils.isEmpty(holderAvatar)) {
            GlideApp.with(mContext)
                    .load(holderAvatar)
                    .centerCrop()
                    .into(ivAvatar);
        }
    }

    @Override
    public void onDistanceUnitChange() {
        mDistanceUnit = DataProvider.getDistanceUnit();
        setDistanceCalories();

    }

    @Override
    public void onSportChallengeChange(CopyOnWriteArrayList<TodayChallenge> todayChallenges) {
        if (mContext == null) {
            return;
        }
        Logger.e("sportChallenge=" + todayChallenges);
        CopyOnWriteArrayList<TodayChallengeBean> todayChallengeBeans = convertSportChallenge2CommonBean(todayChallenges);

        mChallengeAdapter.setDataList(todayChallengeBeans,1);
    }

    private CopyOnWriteArrayList<TodayChallengeBean> convertSportChallenge2CommonBean(CopyOnWriteArrayList<TodayChallenge> todayChallenges) {
        CopyOnWriteArrayList<TodayChallengeBean> todayChallengeBeans = new CopyOnWriteArrayList<>();
        for (TodayChallenge todayChallenge : todayChallenges) {
            TodayChallengeBean todayChallengeBean = new TodayChallengeBean();
            todayChallengeBean.id = (int) todayChallenge.id;
            todayChallengeBean.challengeType = 1;
            todayChallengeBean.sportType = todayChallenge.sportType;
            todayChallengeBean.duration = todayChallenge.duration;
            todayChallengeBean.reminderTime = todayChallenge.reminderTime;
            todayChallengeBean.rewardValue = todayChallenge.rewardValue;
            todayChallengeBean.isCompleted = true;
            todayChallengeBeans.add(todayChallengeBean);
        }
        return todayChallengeBeans;
    }

    @Override
    public void onQuranChallengeChange(CopyOnWriteArrayList<QuranChallenge> quranChallenges) {
        if (mContext == null) {
            return;
        }

        CopyOnWriteArrayList<TodayChallengeBean> todayChallengeBeans = convertQuranChallenge2CommonBean(quranChallenges);

        mChallengeAdapter.setDataList(todayChallengeBeans,0);
    }

    private CopyOnWriteArrayList<TodayChallengeBean> convertQuranChallenge2CommonBean(CopyOnWriteArrayList<QuranChallenge> quranChallenges) {
        CopyOnWriteArrayList<TodayChallengeBean> todayChallengeBeans = new CopyOnWriteArrayList<>();
        for (QuranChallenge quranChallenge : quranChallenges) {
            TodayChallengeBean todayChallengeBean = new TodayChallengeBean();
            todayChallengeBean.id = quranChallenge.id;
            todayChallengeBean.challengeType = 0;
            todayChallengeBean.chapterIndex = quranChallenge.chapterIndex;
            todayChallengeBean.duration = quranChallenge.duration;
            todayChallengeBean.deadline = quranChallenge.deadline;
            todayChallengeBean.rewardValue = quranChallenge.rewardValue;
            todayChallengeBean.isCompleted = true;
            todayChallengeBeans.add(todayChallengeBean);
        }
        return todayChallengeBeans;
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mPresenter != null) {
            mPresenter.stop(mContext);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mPresenter != null) {
            Log.d(TAG, "onResume: ");
            mPresenter.start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }

        StepManager.getInstance().setOnPedometerRegisteredListener(null);
    }

    @Override
    public void onRegistered() {
        Log.d(TAG, "onRegistered: ");
        mPresenter.start();
    }


    @Override
    public void onItemClick(TodayChallengeBean challengeBean) {
        Logger.e("onItemClick,challengeBean=" + challengeBean);
        Intent intent = new Intent();
        if (challengeBean.challengeType == 1) {
            intent.setClassName("com.umeox.moto.watch.fitness", "com.umeox.moto.watch.fitness.ui.ChallengeTipActivity");
            Bundle mBundle = new Bundle();
            mBundle.putLong(EXTRA_KEY_ID, challengeBean.id);
            mBundle.putBoolean(EXTRA_KEY_AUTO, false);
            intent.putExtras(mBundle);
        } else {
            intent.setClassName("com.umeox.quranplayer", "com.umeox.quranplayer.ui.ChallengeTipActivity");
            Bundle mBundle = new Bundle();
            mBundle.putInt(EXTRA_KEY_ID, challengeBean.id);
            intent.putExtras(mBundle);
        }
        startActivity(intent);
    }
}
